package com.simple.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;

public class HttpUtil {
	
	public static String post(String url, int readTimeout, Map<String, String> paramMap) {
		int connectTimeout = 3000;
		String encode = "utf-8";
		HttpURLConnection connection = null;
		String returnString = null;
		BufferedReader in = null;
		try {
			URL requestUrl = new URL(url);
			connection = (HttpURLConnection) requestUrl.openConnection();
			connection.setConnectTimeout(connectTimeout);
			connection.setReadTimeout(readTimeout);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setDoInput(true);
			if (paramMap != null && paramMap.size() > 0) {
				connection.setDoOutput(true);
				StringBuffer params = new StringBuffer();
				for (String key : paramMap.keySet()) {
					params.append(
							URLEncoder.encode(key, encode) + "=" + URLEncoder.encode(paramMap.get(key), encode) + "&");
				}
				String paramString = params.toString();
				paramString = paramString.substring(0, paramString.length() - 1);
				byte[] bypes = paramString.getBytes("ISO-8859-1");
				connection.getOutputStream().write(bypes);
			}
			int statusCode = connection.getResponseCode();
			if (statusCode == 200) {
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				StringBuilder result = new StringBuilder();
				String line;
				long time = System.currentTimeMillis();
				while (System.currentTimeMillis() - time < readTimeout && (line = in.readLine()) != null) {
					result.append(line);
				}
				returnString = result.toString();
			} else {
				throw new Exception("" + statusCode);
			}
			disconnection(connection, in);
		} catch (Exception e) {
			disconnection(connection, in);
			throw new RuntimeException(e);
		}
		return returnString;
	}

	private static void disconnection(HttpURLConnection connection, BufferedReader in) {
		if (in != null) {
			try {
				in.close();
			} catch (Exception e) {

			}
		}
		if (connection != null) {
			try {
				connection.disconnect();
			} catch (Exception e) {

			}
		}
	}

	/**
	 * 上传图片
	 * 
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @return
	 */
	public static String upload(String urlStr, int readTimeout, Map<String, String> textMap, Map<String, byte[]> fileMap) {
		int connectTimeout = 3000;
		String encode = "utf-8";
		String returnString = "";
		HttpURLConnection conn = null;
		String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
		BufferedReader in = null;
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(connectTimeout);
			conn.setReadTimeout(readTimeout);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName
							+ "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			if (fileMap != null) {
				Iterator<Map.Entry<String, byte[]>> iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry<String, byte[]> entry = iter.next();
					String inputName = (String) entry.getKey();
					byte[] inputValue = (byte[]) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					String filename = System.currentTimeMillis() + ".png";
					String contentType = "image/png";

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + URLEncoder.encode(inputName, encode)
							+ "\"; filename=\"" + URLEncoder.encode(filename, encode) + "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

					out.write(strBuf.toString().getBytes("ISO-8859-1"));

					ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(inputValue);
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = byteArrayInputStream.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					byteArrayInputStream.close();
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			int statusCode = conn.getResponseCode();
			if (statusCode == 200) {
				// 读取返回数据
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
				StringBuilder result = new StringBuilder();
				String line;
				long time = System.currentTimeMillis();
				while (System.currentTimeMillis() - time < readTimeout && (line = in.readLine()) != null) {
					result.append(line);
				}
				returnString = result.toString();
			} else {
				throw new Exception("" + statusCode);
			}
			disconnection(conn, in);
		} catch (Exception e) {
			disconnection(conn, in);
			throw new RuntimeException(e);
		}
		return returnString;
	}

	public static String get(String url, int readTimeout) {
		int connectTimeout = 3000;
		HttpURLConnection connection = null;
		String returnString = null;
		BufferedReader in = null;
		try {
			URL requestUrl = new URL(url);
			connection = (HttpURLConnection) requestUrl.openConnection();
			connection.setConnectTimeout(connectTimeout);
			connection.setReadTimeout(readTimeout);
			connection.setRequestMethod("GET");
			connection.setUseCaches(false);
			int statusCode = connection.getResponseCode();
			if (statusCode == 200) {
				// 读取返回数据
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				StringBuilder result = new StringBuilder();
				String line;
				long time = System.currentTimeMillis();
				while (System.currentTimeMillis() - time < readTimeout && (line = in.readLine()) != null) {
					result.append(line);
				}
				returnString = result.toString();
				disconnection(connection, in);
			} else {
				throw new Exception("" + statusCode);
			}
			disconnection(connection, in);
		} catch (Exception e) {
			disconnection(connection, in);
			throw new RuntimeException(e);
		}
		return returnString;
	}
	

	
	private static void close(HttpURLConnection conn) {
		try {
			conn.disconnect();
		} catch (Exception e) {
			conn = null;
		}
	}
	
	private static void close(Closeable obj) {
		try {
			obj.close();
		} catch (Exception e) {
			obj = null;
		}
	}
}
